#include "DirectInit.h"
#include <windows.h>

using namespace std;

DirectInit::DirectInit()
{}

DirectInit::~DirectInit()
{}

bool DirectInit::initialize()
{
	dinput = NULL;
	dikeyboard = NULL;

	//initialize DirectInput object
    HRESULT result = DirectInput8Create(
        GetModuleHandle(NULL), 
        DIRECTINPUT_VERSION, 
        IID_IDirectInput8,
        (void**)&dinput,
        NULL);

	if(FAILED(result))
	{
		MessageBox(NULL, "Could not initialize keyboard", "keyboard not found", NULL);
		return false;
	}

    //initialize the keyboard
    dinput->CreateDevice(GUID_SysKeyboard, &dikeyboard, NULL);
    dikeyboard->SetCooperativeLevel(appWindow, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
	dikeyboard->SetDataFormat(&c_dfDIKeyboard);
    dikeyboard->Acquire();

	return true;
}

//update keyboard
void DirectInit::Update()
{
    dikeyboard->GetDeviceState(sizeof(keys), (LPVOID)&keys);
}

//Return key press state
int DirectInit::Key_Down(int key)
{
	return (keys[key] & 0x80);
}

void DirectInit::Shutdown()
{
	// Release the keyboard.
	if(dikeyboard)
	{
		dikeyboard->Unacquire();
		dikeyboard->Release();
		dikeyboard = 0;
	}

	// Release the main interface to direct input.
	if(dinput)
	{
		dinput->Release();
		dinput = 0;
	}
}